package com.longrise.android.byjk.plugins.course.batchbuy;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.AllCourseChildBean;
import com.longrise.android.byjk.model.AllCourseParentBean;
import com.longrise.android.byjk.plugins.course.batchbuy.batchbuyconfirm.BatchbuyConfirmActivity;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.android.byjk.widget.view.MarqueeView;
import com.longrise.common.base.BaseActivity2;
import com.longrise.common.eventbean.PayEventBean;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.common.utils.UmengStatisticsUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by callxkj on 2017/11/17.
 * 批量购买
 */

public class BatchbuyActivity extends BaseActivity2<BatchbuyPresenter> implements
        BatchbuyContract.View, View.OnClickListener {

    private RecyclerView mRcv1; //左边rcv
    private ImageView mIvtitle;
    private RecyclerView mRcv2;
    private BatchbuyAdapter1 mAdapter1;
    private BatchbuyAdapter2 mAdapter2;
    private MarqueeView mMarquee;
    private ArrayList<AllCourseChildBean> mSelectedCourseBeans = new ArrayList<AllCourseChildBean>();
    private TextView mTvgray;
    private RelativeLayout mRlconfirm;
    private TextView mTvconfirm;
    private TextView mTvconfim_num;
    private RelativeLayout mRldiscount;
    private TextView mTvdiscountPrice;
    private TextView mTvdiscountPriceDesc;
    private TextView mTvzhj;

    private ArrayList<String> mTipslist = new ArrayList<>();
    private RelativeLayout mRlmarquee;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_batchbuy;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        setToolbarTitle("批量购买");
        mRcv1 = (RecyclerView) findViewById(R.id.batchbuy_rcv1);
        mIvtitle = (ImageView) findViewById(R.id.batchbuy_iv);
        mRcv2 = (RecyclerView) findViewById(R.id.batchbuy_rcv2);
        mTvgray = (TextView) findViewById(R.id.batchbuy_tvgray);
        mRlconfirm = (RelativeLayout) findViewById(R.id.batchbuy_rl_confirm);
        mTvconfirm = (TextView) findViewById(R.id.batchbuy_tv_confirm);
        mTvconfim_num = (TextView) findViewById(R.id.batchbuy_tv_confirm_num);
        mRldiscount = (RelativeLayout) findViewById(R.id.batchbuy_zhj_rl);
        mTvdiscountPrice = (TextView) findViewById(R.id.batchbuy_tvzkj_price);
        mTvdiscountPriceDesc = (TextView) findViewById(R.id.batchbuy_tvzkj_price_desc);
        mTvzhj = (TextView) findViewById(R.id.batchbuy_tvzhj);
        mRlmarquee = (RelativeLayout) findViewById(R.id.batchbuy_rl_marquee);
        mMarquee = (MarqueeView) findViewById(R.id.batchbuy_MarqueeView);

        resizeIv();
        initRcv();
        initEvent();

        UmengStatisticsUtil.onEvent("buy_system" + (1));//首次进入页面 默认选择第一个
    }

    @Override
    public void onToolbarBackClick() {
        UmengStatisticsUtil.onEvent("buy_return");
        finish();
    }

    private void initRcv() {
        mAdapter1 = new BatchbuyAdapter1();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRcv1.setLayoutManager(linearLayoutManager);
        mRcv1.setAdapter(mAdapter1);

        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(mContext);
        linearLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        mAdapter2 = new BatchbuyAdapter2();
        mRcv2.setLayoutManager(linearLayoutManager2);
        mRcv2.setAdapter(mAdapter2);
    }

    private void resizeIv() {
        int width = AppUtil.getScreenWidth() - AppUtil.dip2px(124);
        int height = (int) (width * (float) 11 / 25);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mIvtitle.getLayoutParams();
        layoutParams.height = height;
        mIvtitle.setLayoutParams(layoutParams);
    }

    private void initEvent() {
        mRlconfirm.setOnClickListener(this);
        mRlmarquee.setOnClickListener(this);
        mIvtitle.setOnClickListener(this);
        //左边rcv的item点击事件
        mAdapter1.setOnBatchbuyParentItemClickListener(new BatchbuyAdapter1.OnItemClickListener() {
            @Override
            public void onClick(String assortmenttypekey) {
                mAdapter2.setDatas(null);
                mPresenter.loadAdapter2Data(assortmenttypekey);
            }
        });

        //右边课程item的点击事件
        mAdapter2.setOnItemClickListener(new BatchbuyAdapter2.OnBatchbuydetailClickListener() {
            @Override
            public void onClick(AllCourseChildBean itembean) {
                if (mSelectedCourseBeans.contains(itembean)) {
                    mSelectedCourseBeans.remove(itembean);
                } else {
                    mSelectedCourseBeans.add(itembean);
                }
                mAdapter2.setSelectedCourseBeans(mSelectedCourseBeans);
                mPresenter.calculatePrice(mSelectedCourseBeans);
            }
        });

        //点击跑马灯
        mMarquee.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                toShowDiscountMsg();
            }
        });
    }

    /**
     * 使用了errorpage
     */
    @Override
    public void reload() {
        super.reload();
        mPresenter.init();
    }

    /**
     * 初始化左边的adapter
     */
    @Override
    public void initFirstAdapter(List<AllCourseParentBean> parentList) {
        mAdapter1.setDatas(parentList);
        String assortmenttype = parentList.get(0).getAssortmenttype();
        mPresenter.loadAdapter2Data(assortmenttype);
    }

    @Override
    public void refreshSecondAdapter(List<AllCourseChildBean> childList) {
        mAdapter2.setDatas(childList);
    }

    @Override
    public void showTips(String[] tips) {
        mTipslist.clear();
        for (int x = 0; x < tips.length; x++) {
            mTipslist.add(tips[x]);
        }
        mMarquee.startWithList(mTipslist);
    }

    /**
     * 显示底部的折扣信息
     *
     * @param courseNum         购买的课程数量
     * @param isSelected        是否有选择课程
     * @param discountratePrice 打折后的总价
     * @param discountPriceDesc 左下角的提示语
     * @param zhj               显示折后价 或者 实付款
     */
    @Override
    public void showDiscountratePrice(boolean isSelected, String courseNum, String discountratePrice,
                                      String discountPriceDesc, String zhj) {
        if (isSelected) {
            mRlconfirm.setClickable(false);
            mTvgray.setVisibility(View.GONE);
            mRldiscount.setVisibility(View.VISIBLE);
            mTvdiscountPriceDesc.setVisibility(View.VISIBLE);
            mTvconfim_num.setVisibility(View.VISIBLE);
            mTvdiscountPrice.setText("¥" + discountratePrice);
            mTvdiscountPriceDesc.setText(discountPriceDesc);
            mTvconfim_num.setText("（" + courseNum + "）");
            mTvconfirm.setTextColor(Color.parseColor("#ffffff"));
            mRlconfirm.setBackgroundResource(R.drawable.by_bg_bt_square_selector);
            mRlconfirm.setClickable(true);
            mTvzhj.setText(zhj);

        } else {//没有选择课程 则显示灰色提示
            mTvgray.setVisibility(View.VISIBLE);
            mRldiscount.setVisibility(View.GONE);
            mTvdiscountPriceDesc.setVisibility(View.GONE);
            mTvconfim_num.setVisibility(View.GONE);
            mTvgray.setText(Html.fromHtml("<font color='#C1C1C1'>折后价：</font>" + "<font color='#CCCCCC'>¥0.00</font>"));
            mRlconfirm.setBackgroundColor(Color.parseColor("#D8D8D8"));
            mTvconfirm.setTextColor(Color.parseColor("#B3B3B3"));
            mRlconfirm.setClickable(false);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.batchbuy_rl_confirm:
                toConfirm();
                UmengStatisticsUtil.onEvent("buy_confirm");
                break;
            case R.id.batchbuy_rl_marquee:
                toShowDiscountMsg();
                UmengStatisticsUtil.onEvent("buy_salerule");
                break;
            case R.id.batchbuy_iv:
                toBuyAll();
                UmengStatisticsUtil.onEvent("buy_banner");
                break;
            case R.id.tv_cancel: //弹出dialog的 我知道了
                UmengStatisticsUtil.onEvent("buy_salerule_ok");
                DialogUtil.getInstance().dismiss();
                break;
            case R.id.tv_confirm:  //弹出dialog的 立即购买
                UmengStatisticsUtil.onEvent("buy_salerule_confirm");
                Bundle bundletype9 = new Bundle();
                bundletype9.putString(BatchbuyConfirmActivity.ORDERTYPE, BatchbuyConfirmActivity.BUY_ALL);
                startActivity(BatchbuyConfirmActivity.class, bundletype9);
                DialogUtil.getInstance().dismiss();
                break;
        }
    }

    /**
     * 立即购买
     */
    private void toConfirm() {
        Intent intent = new Intent(this, BatchbuyConfirmActivity.class);
        intent.putExtra(BatchbuyConfirmActivity.ORDERTYPE, BatchbuyConfirmActivity.BUY_MULTIPLE);
        intent.putParcelableArrayListExtra(BatchbuyConfirmActivity.SELECTLIST, mSelectedCourseBeans);
        startActivity(intent);
    }

    /**
     * 弹出折扣的弹窗
     */
    private void toShowDiscountMsg() {
        View dialogview = View.inflate(this, R.layout.dialog_discount_msg, null);
        LinearLayout ll = (LinearLayout) dialogview.findViewById(R.id.dialog_discount_msg_ll);
        TextView tv_cancel = (TextView) dialogview.findViewById(R.id.tv_cancel);
        TextView tv_confirm = (TextView) dialogview.findViewById(R.id.tv_confirm);
        tv_cancel.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);
        for (String msg : mTipslist) {
            TextView tv = new TextView(this);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
            tv.setTextColor(Color.parseColor("#000000"));
            // tv.setLayoutParams(new LinearLayout.LayoutParams());
            tv.setText(msg);
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, AppUtil.dip2px(15));
            layoutParams.topMargin = AppUtil.dip2px(5);
            layoutParams.gravity = Gravity.CENTER;
            tv.setLayoutParams(layoutParams);
            ll.addView(tv);
        }
        DialogUtil.getInstance().creatAlertDialog(this, dialogview, 266, 240);
    }

    /**
     * 一键购买全部
     */
    private void toBuyAll() {
        Bundle bundle = new Bundle();
        bundle.putString(BatchbuyConfirmActivity.ORDERTYPE, BatchbuyConfirmActivity.BUY_ALL);
        startActivity(BatchbuyConfirmActivity.class, bundle);
    }

    /**
     * 支付成功后关闭页面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPayResult(PayEventBean bean) {
        if (bean.isClosePage()) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            UmengStatisticsUtil.onEvent("buy_return");
        }
        return super.onKeyDown(keyCode, event);
    }
}
